package com.example.administrator.solution;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.obsez.android.lib.filechooser.ChooserDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity {

    private TextView vwEdtFileName;
    private ImageView vwChooseFile;
    private Button vwSendFile;
    private TextView vwTxtPercentage;
    private ProgressBar vwProgressBar;
    private TextView vwTvLogsText;

    private String _path;
    private File _file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){

        }
        vwEdtFileName = findViewById(R.id.vw_edt_file_name);
        vwEdtFileName.setFocusable(false);
        vwEdtFileName.setFocusableInTouchMode(false);
        vwChooseFile = findViewById(R.id.vw_choose_file);
        vwSendFile = findViewById(R.id.vw_send_file);
        vwTxtPercentage = findViewById(R.id.vw_txt_percentage);
        vwProgressBar = findViewById(R.id.vw_progress_bar);
        vwTvLogsText = findViewById(R.id.vw_tvLogs_text);


        fileChooserDialog();



        vwChooseFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fileChooserDialog();
            }
        });
        vwSendFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(_file!=null){
                    sendFile();
                }
            }
        });

    }

    private void fileChooserDialog() {

        new ChooserDialog().with(MainActivity.this)
                .withStartFile(_path)
                .withChosenListener(new ChooserDialog.Result() {
                    @Override
                    public void onChoosePath(String path, File pathFile) {
                        //Toast.makeText(MainActivity.this, "FILE: " + path, Toast.LENGTH_SHORT).show();
                        vwEdtFileName.setText(pathFile.getName());
                        _path = path;
                        _file = pathFile;
                        vwTxtPercentage.post(new Runnable() {
                            @Override
                            public void run() {
                                vwTvLogsText.setText("selected a file at "+_path+".\r\n"+vwTvLogsText.getText());
                            }
                        });
                    }
                })
                .withOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                    }
                })
                .build()
                .show();
    }

    private void sendFile(){
        SharedPreferences sp = this.getSharedPreferences("settings", Activity.MODE_PRIVATE);
        final String hostname = sp.getString("hostname","192.168.1.106");
        final int port = Integer.parseInt(sp.getString("port","60000"));
        Log.v("console","path:"+_path+",filename:"+_file);
        final File file = new File(_path);
        final String filename = file.getName();
        Log.v("console","filename:"+filename);

        new Thread(){
            @Override
            public void run() {
                Log.v("console", "start to transfer the file "+filename);
                Socket socket = null;
                OutputStream os = null;
                InputStream is = null;
                try{
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(hostname, port));
                    Log.v("console", "connected to "+hostname+":"+port);


                    vwTxtPercentage.post(new Runnable() {
                        @Override
                        public void run() {
                            vwTvLogsText.setText("connect to server:"+hostname+" port:"+port+".\r\n"+vwTvLogsText.getText());
                        }
                    });

                    os = socket.getOutputStream();
                    is = socket.getInputStream();

                    byte[] fileNameBytes = filename.getBytes("UTF8");
                    int fileNameBytesSize = fileNameBytes.length;

                    os.write(fileNameBytesSize);
                    os.flush();
                    os.write(fileNameBytes);
                    os.flush();
                    byte[] existsBytes = new byte[4];
                    int len = is.read(existsBytes);

                    int exists = ByteBuffer.wrap(existsBytes).asIntBuffer().get();

                    if(exists==0){
                        Log.v("console", "The file is't exists on server.");
                        byte[] buff = new byte[5120];
                        FileInputStream fis = null;

                        vwProgressBar.setMax(0);
                        vwProgressBar.setMax((int)file.length());
                        vwProgressBar.setProgress(0);
                        vwTxtPercentage.post(new Runnable() {
                            @Override
                            public void run() {
                                vwTxtPercentage.setText("0%");
                            }
                        });
                        try {
                            fis = new FileInputStream(file);
                            while ((len = fis.read(buff)) >= 0) {
                                vwProgressBar.setProgress(vwProgressBar.getProgress()+len);
                                final String text = new DecimalFormat("#00.##").format(((float)vwProgressBar.getProgress()/(float)vwProgressBar.getMax())*100);

                                vwTxtPercentage.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        vwTxtPercentage.setText(text+"%");
                                        vwTvLogsText.setText("send "+text+"% \r\n"+vwTvLogsText.getText());
                                    }
                                });

                                os.write(buff, 0, len);
                            }
                            os.flush();
                        }finally {
                            if(fis!=null){
                                try {
                                    fis.close();
                                }catch(Exception ex){
                                    Log.w("console",ex.getLocalizedMessage(), ex);
                                }
                            }
                        }
                        vwTxtPercentage.post(new Runnable() {
                            @Override
                            public void run() {
                                vwTvLogsText.setText("file:"+filename+" was finish.\r\n"+vwTvLogsText.getText());
                            }
                        });
                    }else{
                        vwTxtPercentage.post(new Runnable() {
                            @Override
                            public void run() {
                                vwTvLogsText.setText("The file:"+filename+" is exists on server.\r\n"+vwTvLogsText.getText());
                            }
                        });
                    }

                } catch (final IOException e) {
                    Log.w("console", e.getLocalizedMessage(), e);
                    vwTxtPercentage.post(new Runnable() {
                        @Override
                        public void run() {
                            vwTvLogsText.setText("transfer error:"+e.getLocalizedMessage()+"\r\n"+vwTvLogsText.getText());
                        }
                    });
                } finally {

                    if(is!=null){
                        try {
                            is.close();
                        } catch (IOException e) {
                            Log.w("console", e.getLocalizedMessage(), e);
                        }
                    }

                    if(os!=null){
                        try {
                            os.close();
                        } catch (IOException e) {
                            Log.w("console", e.getLocalizedMessage(), e);
                        }
                    }

                    if(socket!=null&&socket.isConnected()){
                        try {
                            socket.close();
                        } catch (IOException e) {
                            Log.w("console", e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }.start();

    }

    //  menu icon
    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_gotosetting, menu);

        if(menu instanceof MenuBuilder){
            MenuBuilder m = (MenuBuilder) menu;
            //noinspection RestrictedApi
            m.setOptionalIconsVisible(true);
        }

        return super.onCreateOptionsMenu(menu);
    }
    // Option Menu Click Listener
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.setting:
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
